< previous page page_219 next page >

Page 219
0219-01.jpg
Figure 10.5
You set up watches in the Add Watch dialog box.
Error Trapping
As you are writing code, Visual Basic informs you of syntactical errors. However, once the program is running, you may encounter unexpected runtime errors in many circumstances. For example, suppose you try to open a text file that the user has deleted. When a compiled program has an error like this, an error message is displayed, as shown in Figure 10.6, and the program ends.
0219-02.jpg
Figure 10.6
You can avoid cryptic error
messages and ungraceful exits by
adding error handling to your application.
Although you cannot predict and write code for every possible type of error, File Not Found errors, such as the one in Figure 10.6, are fairly easy to handle. If you do not write code to work around the error, you can at least provide a message that makes more sense before ending the program.
Using the On Error Statement
The most common way to handle error conditions is to use Visual Basic's On Error statement. The On Error statement interrupts the normal flow of your program when an error occurs and begins executing your error handling code. A typical use is as follows:
On Error Goto FileOpenError
When this statement is executed, any errors that occur in subsequent statements cause Visual Basic to stop the normal line-by-line execution and jump to the statement labeled as FileOpenError.
Labeling Code Lines
This discussion brings up another new concept: line labels. If you have used an early version of BASIC, you may remember statements with line numbers, like this:

 
< previous page page_219 next page >